﻿using Microsoft.Extensions.Configuration;
using System.Reflection;
using System.Collections.Generic;

namespace MiniFox.Configurations
{
    /// <summary>
    /// 
    /// </summary>
    public class JsonConfigurationFactory : ConfigurationFactory
    {
        const string COMMON_SETTINGS = "minifox:settings";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="configuration"></param>
        public JsonConfigurationFactory(IConfiguration configuration)
        {
            _configuration = configuration;
        }
        IConfiguration _configuration;
        /// <summary>
        /// 
        /// </summary>
        protected IConfiguration Configuration
        {
            get
            {
                return _configuration;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="configType"></param>
        /// <param name="sectionName"></param>
        /// <returns></returns>
        protected internal override object GetConfiguration(Type configType, string sectionName)
        {
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                var attr = configType.GetCustomAttribute<SectionAttribute>();
                if (attr != null)
                {
                    sectionName = attr.SectionName;
                }
            }
            if (string.IsNullOrWhiteSpace(sectionName))
            {
                throw new InvalidOperationException();
            }
            var section = this.Configuration.GetSection(sectionName);

            try
            {
                var config = section.Get(configType);

                //以下为容错代码
                if (config == null)
                    config = Activator.CreateInstance(configType);
                return config;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override Dictionary<string, string> Settings
        {
            get
            {
                return this.GetConfiguration<Dictionary<string, string>>(COMMON_SETTINGS);
            }
        }
    }
}
